package com.haixiaoke.saas.enterprise.lock.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.haixiaoke.saas.common.annotation.Log;
import com.haixiaoke.saas.common.annotation.TenantScope;
import com.haixiaoke.saas.common.config.DevicesConfig;
import com.haixiaoke.saas.common.constant.LockConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.enums.BusinessType;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.lock.domain.HouseLock;
import com.haixiaoke.saas.lock.domain.LockFace;
import com.haixiaoke.saas.lock.domain.LockPwd;
import com.haixiaoke.saas.lock.service.IHouseLockService;
import com.haixiaoke.saas.system.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

import static com.haixiaoke.saas.common.tenant.TenantContext.getTenantId;


/**
 * 房间锁信息Controller
 *
 * @author qixi
 * @date 2024-07-25
 */
@RestController
@RequestMapping("/enterprise/lock/houseLock")
public class EnterpriseHouseLockController extends BaseController {
    @Autowired
    private IHouseLockService houseLockService;

    @Autowired
    private DevicesConfig devicesConfig;

    /**
     * 查询房间锁信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:houseLock:list')")
    @GetMapping("/list")
    public TableDataInfo list(HouseLock houseLock) {
        startPage();
        houseLock.setTenantId(getTenantId());
        List<HouseLock> list = houseLockService.selectHouseLockList(houseLock);
        return getDataTable(list);
    }

    /**
     * 获取房间锁信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:houseLock:query')")
    @GetMapping(value = "/{lockId}")
    public AjaxResult getInfo(@PathVariable("lockId") Long lockId) {
        return success(houseLockService.selectHouseLockByLockId(lockId));
    }

    /**
     * 新增房间锁信息
     */
    @PreAuthorize("@ss.hasPermi('business:houseLock:add')")
    @Log(title = "房间锁信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HouseLock houseLock) {
        return toAjax(houseLockService.insertHouseLock(houseLock));
    }

    /**
     * 修改房间锁信息
     */
    @PreAuthorize("@ss.hasPermi('business:houseLock:edit')")
    @Log(title = "房间锁信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HouseLock houseLock) {
        return toAjax(houseLockService.updateHouseLock(houseLock));
    }

    /**
     * 删除房间锁信息
     */
    @PreAuthorize("@ss.hasPermi('business:houseLock:remove')")
    @Log(title = "房间锁信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{lockIds}")
    public AjaxResult remove(@PathVariable Long[] lockIds) {
        return toAjax(houseLockService.deleteHouseLockByLockIds(lockIds));
    }

    /**
     * 新增房间锁信息
     */
    @PreAuthorize("@ss.hasPermi('business:houseLock:create')")
    @PostMapping("/create")
    @TenantScope
    public AjaxResult create(@RequestBody @Valid HouseLock houseLock) {
        houseLock.setTenantId(getTenantId());
        houseLock.setCreateBy(getUsername());
        checkHouseLock(houseLock);
        int houseLock1 = houseLockService.createHouseLock(houseLock);
        return toAjax(houseLock1);
    }

    private void checkHouseLock(HouseLock houseLock) {
        String mac = houseLock.getMac();
        HouseLock houseLock1 = houseLockService.selectHouseLockByMac(mac, houseLock.getTenantId());
        if (ObjectUtil.isNotNull(houseLock1)) {
            throw new ServiceException("该智能锁MAC地址已被绑定");
        }

        String lockName = houseLock.getLockName();
        HouseLock houseLock2 = houseLockService.selectHouseLockByLockName(lockName, houseLock.getTenantId());
        if (ObjectUtil.isNotNull(houseLock2)) {
            throw new ServiceException("该智能锁名称已被绑定");
        }

    }


    /**
     * 获取锁型号列表
     */
    @GetMapping("/model/list")
    public AjaxResult modelList() {
        JSONObject o = devicesConfig.sendRequest(RequestMethod.GET, null, "/business/model/list");
        return success(o.getJSONArray("data"));
    }

    /**
     * 换房
     */
    @PreAuthorize("@ss.hasPermi('business:houseLock:changeRoom')")
    @PutMapping("/changeRoom")
    @TenantScope
    public AjaxResult changeRoom(@RequestBody HouseLock houseLock) {
        houseLock.setTenantId(getTenantId());
        houseLock.setCreateBy(getUsername());
        return toAjax(houseLockService.changeRoom(houseLock));
    }

    /**
     * 新增人脸
     */
    @PostMapping("/addFace")
    @TenantScope
    public AjaxResult addFace(@RequestBody @Valid LockFace lockFace) {
        lockFace.setTenantId(getTenantId());
        lockFace.setCreateBy(getUsername());
        lockFace.setUserType(LockConstants.USER_TYPE_MANAGER);
        return toAjax(houseLockService.insertLockFace(lockFace));
    }


    /**
     * 删除人脸
     */
    @GetMapping("/removeFace/{faceId}")
    @TenantScope
    public AjaxResult removeFace(@PathVariable Long faceId) {
        return toAjax(houseLockService.removeLockFace(faceId));
    }


    /**
     * 新增密码
     */
    @PostMapping("/addPwd")
    @TenantScope
    public AjaxResult addPwd(@RequestBody @Valid LockPwd lockPwd) {
        lockPwd.setTenantId(getTenantId());
        lockPwd.setCreateBy(getUsername());
        return toAjax(houseLockService.insertLockPwd(lockPwd));
    }

    /**
     * 删除密码
     */
    @GetMapping("/removePwd/{pwdId}")
    @TenantScope
    public AjaxResult removePwd(@PathVariable Long pwdId) {
        return toAjax(houseLockService.removeLockPwd(pwdId));
    }


    /**
     * 外开门记录
     */
    @PreAuthorize("@ss.hasPermi('business:houseLock:outerOpenDoorRecord')")
    @PostMapping("/outerOpenDoorRecord")
    @TenantScope
    public TableDataInfo outerOpenDoorRecord(@RequestParam(value = "lockId") Long lockId,
                                             @RequestParam(value = "identificationd", required = false) String identification,
                                             @RequestParam(value = "startTime", required = false) Date startTime,
                                             @RequestParam(value = "endTime", required = false) Date endTime,
                                             @RequestParam(value = "unlockType", required = false) Integer unlockType,
                                             @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                             @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        return houseLockService.outerOpenDoorRecord(lockId, identification, startTime, endTime, unlockType, pageNum, pageSize);
    }

    /**
     * 删除锁
     */
    @PreAuthorize("@ss.hasPermi('business:houseLock:removeLock')")
    @DeleteMapping("/removeLock/{lockId}")
    @TenantScope
    public AjaxResult lockId(@PathVariable Long lockId) {
        return toAjax(houseLockService.removeLock(lockId));
    }


    /**
     * 修改锁冻结状态
     */
    @PreAuthorize("@ss.hasPermi('business:houseLock:updateLock')")
    @PutMapping("/updateLock")
    @TenantScope
    public AjaxResult updateLockStatus(@RequestBody HouseLock houseLock) {
        if (StrUtil.isEmpty(houseLock.getLockName())) {
            throw new ServiceException("锁名称不能为空");
        }
        houseLock.setUpdateBy(getUsername());
        return toAjax(houseLockService.updateLockStatus(houseLock));
    }


    /**
     * 重新授权人脸
     */
    @PostMapping("/reAuthFace")
    @TenantScope
    public AjaxResult reAuthFace(@RequestBody LockFace lockFace) {
        if (ObjectUtil.isEmpty(lockFace.getFaceId())) {
            throw new ServiceException("人脸信息不能为空");
        }
        lockFace.setUpdateBy(getUsername());
        return toAjax(houseLockService.reAuthFace(lockFace));
    }


}
